package com.erlin.common.utils;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.erlin.common.config.OssConfig;
import com.erlin.common.exception.ElException;
import com.erlin.common.exception.ElParamException;
import com.erlin.common.vo.FileUploadResultVo;
import com.erlin.platform.service.IElFileService;
import com.erlin.platform.service.bo.FileUploadBo;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Objects;

/**
 * alin  文件上传工具
 */
@Service
public class FileUploadUtil {
    //简单的图片上传处理，后期完善
    private static final List<String> IMAGE_TYPE = List.of("jpg", "jpeg", "gif", "png");

    @Autowired
    private OSS ossClient;
    @Autowired
    private OssConfig ossConfig;
    @Autowired
    private IElFileService elFileService;

    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    public FileUploadResultVo uploadImg(MultipartFile multipartFile) {
        //简单校验文件名，TODO 后期修改
        String filename = multipartFile.getOriginalFilename();
        assert filename != null;
        String suffix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
        if (!IMAGE_TYPE.contains(suffix)) {
            throw new ElParamException("file.image.type.error");
        }
        String filePath = getFilePath(filename);
        try {
            ossClient.putObject(ossConfig.getBucket(), filePath, new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (Exception e) {
            //TODO 日志输出
            e.printStackTrace();
            throw new ElException("file.upload.error");
        }
        return elFileService.insertFile(new FileUploadBo(multipartFile, filePath));
    }

    /**
     * 生成路径以及文件名 例如：//images/2019/04/28/15564277465972939.jpg
     */
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

}
